<?php
/**
 * JoiGallery - image gallery component for Joostina
 *
 * Frontend event handler
 *
 * @version 1.0 alpha 3
 * @package JoiGallery
 * @filename joigallery.php
 * @author JoostinaTeam
 * @copyright (C) 2008-2009 Joostina Team
 * @license see license.txt
 *
 **/

// запрет прямого доступа
defined('_VALID_MOS') or die();

require_once ($mainframe->getPath('class'));
require_once ($mainframe->getPath('front_html'));

$my->_gid = joiGalleryHelper::get_my_gid();
//$my->_gid = $gid = intval($my->gid);

//Подключаем js
joiGalleryHelper::_load_core_js();
//Подключаем CSS
$mainframe->addCSS($mainframe->getCfg('live_site') . '/components/com_joivideo/css/style.css');	

//Загружаем настройки
$params = _setup();

switch ($params->_act) {

	case 'photos':
		_photos($params);
		break;
	default:

	case 'category':
	case 'categories':
		_categories($params);
		break;
}

function _photos($params) {

	$id = intval(mosGetParam($_REQUEST, 'id', 0));

	switch ($params->_task) {
		case 'new':
			HTML_joigallery::newPhoto($params);
			break;
		case 'process_upload':
			_process_upload($params);
			break;
		case 'edit':
			edit_photo($params->_cid, $params);
			break;
		case 'apply':
		case 'save':
			update_photo($params);
			break;
		case 'remove':
			remove_photo($params->_cid, $params);
			break;
		case 'cancel':
			_cancel('photos', $id, $params);
			break;
		default:
			view_photo($params->_cid, $params);
			break;
	}
}

function _categories($params) {

	$id = intval(mosGetParam($_REQUEST, 'id', 0));

	switch ($params->_task) {
		case 'new':
			edit_category(0, $params);
			break;
		case 'edit':
			edit_category($params->_cid, $params);
			break;
		case 'apply':
		case 'save':
			save_category();
			break;
		case 'cancel':
			_cancel('categories', $id, $params);
			break;
		case 'remove':
			remove_category($params->_cid, $params);
			break;
		default:
			show_category($params->_cid, $params);
			break;
	}
}

function _cancel($act, $id, $params) {
	mosRedirect('index.php?option=' . $params->_option . ($id > 0 ? '&amp;act=' . $act . '&amp;cid=' . $id : '') . '&amp;Itemid=' . $params->_Itemid);
}

/**
 * Загрузка настроек
 */
function _setup() {
	global $Itemid, $my;


	$mainframe = &mosMainFrame::getInstance();
	$database = $mainframe->_db;

	$group = mosGetParam($_REQUEST, 'cid', 'default');
	$params = new joiGalleryConfig($database, 'joigallery', $group);

	$params->_option = mosGetParam($_REQUEST, 'option');
	$params->_task = mosGetParam($_REQUEST, 'task');
	$params->_Itemid = mosGetParam($_REQUEST, 'Itemid', '');
	$params->_limitstart = intval(mosGetParam($_REQUEST, 'limitstart'));
	$params->_limit = intval(mosGetParam($_REQUEST, 'limit', $params->thumbnails_limit));
	$params->_act = mosGetParam($_REQUEST, 'act');

	$params->_cid = mosGetParam($_REQUEST, 'cid', $params->get('cid', 0));
	if (is_array($params->_cid)) {
		$params->_cid = $params->_cid[0];
	}
	//Права пользователей
	$accsess = new joiGalleryRights($params->u_rights);
	$params->_access = $accsess;

	return $params;
}

/**
 * Загрузка изображения
 */
function _process_upload($params) {
    global $my;
    $mainframe = &mosMainFrame::getInstance();
	$return = processImage::upload_handler($params);

	if ($return == 1) {
		$msg = 'Изображение было успешно добавлено.';
	}else {
		$msg = 'Изображения ('.$return.') успешно добавлены.';
	}
    
    if( !$params->get('add_image_pubunpub', 1) || (
            !$params->_access->allow_me('set_state', $my->_gid)  || !$params->_access->allow_me('set_state_own', $my->_gid) 
    ) ){
         if($params->_access->allow_me('no_premoderate', $my->_gid)){
            if($return == 1){
                $redirect_photo = 1;     
            }
            else{
                $redirect_photo = 0;    
            }
               
         }
         else{
            $redirect_photo = 0; 
            if($return == 1){
                $msg .= ' Оно будет опубликовано после проверки модератором.'; 
            }
 
         }
    }
    
    if(!$redirect_photo){
        mosRedirect('index.php?option=' . $params->_option . '&act=categories&cid=' . $params->_cid . '&Itemid=' . $params->_Itemid, $msg);    
    }
    else{
        mosRedirect('index.php?option=' . $params->_option . '&act=categories&cid=' . $params->_cid . '&Itemid=' . $params->_Itemid, $msg);    
    }

	
}

/**
 * Редактирование изображения
 */
function edit_photo($id, $params) {
	global $my;

	$database = &database::getInstance();

	$photo = new joiGalleryPhoto($database);
	$photo->load($id);

	$categories = joiGalleryCategory::getCategorieTree();
/**
 * 	$obj = new stdClass();
 * 	$obj->id = 0;
 * 	$obj->name = ' - select - ';
 * 	array_unshift($categories, $obj);
 */
	$photo->catlist = $categories;

	HTML_joigallery::editPhoto($photo, $params);

}

/**
 * Сохранение отредактированнной информации
 */
function update_photo($params) {
	global $my;

    $mainframe = &mosMainFrame::getInstance();
	$database = $mainframe->_db;

	if (!$my->id && $my->gid != 2) {
		mosNotAuth();
		return;
	}

	$photo = new joiGalleryPhoto($database);
	$photo->bind($_POST);

	$photo->default = intval(mosGetParam($_REQUEST, 'default', 0));

	if ($photo->default) {
		$photo->clean_default($photo->cid);
	}

	if (!$photo->id) {
		$photo->ordering = 999999999;
	}

	if (!$photo->check()) {
		echo "<script> alert('" . $photo->getError() . "'); window.history.go(-1); </script>\n";
		exit();
	}
	if (!$photo->store()) {
		echo "<script> alert('" . $photo->getError() . "'); window.history.go(-1); </script>\n";
		exit();
	}

	$photo->updateOrder('cid = ' . (int)$photo->cid);
    
    //Дополнительные поля
    $extra_fields = new joiExtraFields($mainframe, 'com_joivideo');
    $extra_fields->save_fields_values($photo->id);

	switch ($params->_task) {
		case 'save':
			mosRedirect('index.php?option=' . $params->_option . '&act=photos&cid=' . $photo->id . '&Itemid=' . $params->_Itemid);
			break;
		case 'apply':
			mosRedirect('index.php?option=' . $params->_option . '&act=photos&task=edit&cid=' . $photo->id . '&Itemid=' . $params->_Itemid);
			break;
	}
}

/**
 * Просмотр фото
 */
function view_photo($id, $params) {
	global $my;
	$database = &database::getInstance();

	$row = new joiGalleryPhoto($database);
	$row->load($id);

	$row = $row->get_img_atribs($row, $params);

	$cat = new joiGalleryCategory($database);
	$cat->load($row->cid);

	if (($cat->id > 0) && ($cat->access > $my->gid) || ($row->state < 1 && $my->gid != 2) || ($cat->published < 1 && $my->gid != 2 && $cat->id)) {
		mosNotAuth();
		return;
	}

	$user = new mosUser($database);
	$user->load($row->user_id);
	$row->user = $user;

    $row->next = $row->get_next($row, $params);
    $row->prev = $row->get_prev($row, $params);

	HTML_joigallery::showPhoto($row, $params);
}

/**
 * Удаление фото
 */
function remove_photo($id, $params) {
	global $my;

	if(!$params->_access->allow_me('del_photo', $my->_gid)) {
		joiGalleryError::error($params->_access->error('del_photo'));
	}

    $mainframe = &mosMainFrame::getInstance();
	$database = $mainframe->_db;

	$row = new joiGalleryPhoto($database);

	$row->load($id);

	if($my->id == $row->user_id && !$params->_access->allow_me('del_own_photo', $my->_gid)) {
		joiGalleryError::error($params->_access->error('del_own_photo'));
		return false;
	}

	if($my->id != $row->user_id && !$params->_access->allow_me('del_photo', $my->_gid)) {
		joiGalleryError::error($params->_access->error('del_own_photo'));
		return false;
	}


	$row->remove_images($row, $params);
	$row->delete();
	$row->updateOrder('cid = ' . $row->cid);
    
    $row->check_main_photo($row->cid);
    
    //Дополнительные поля
    $extra_fields = new joiExtraFields($mainframe, 'com_joivideo');
    $extra_fields->delete_values_by_obj($row->id);

	mosRedirect(sefRelToAbs('index.php?option=' . $params->_option . '&act=categories&cid=' . $row->cid . '&Itemid=' . $params->_Itemid));

}

function edit_category($id, $params) {
	global $database, $my;

	if (!$my->id && $my->gid != 2) {
		mosNotAuth();
		return;
	}

	$cat = new joiGalleryCategory($database);
	$cat->load($id);

	if (!$cat->id) {
		$cat->published = 1;
		$cat->parent_id = intval(mosGetParam($_REQUEST, 'cid', 0));
	}

	$categories = joiGalleryCategory::getCategorieTree();
	$obj = new stdClass();
	$obj->id = 0;
	$obj->name = 'Top';
	array_unshift($categories, $obj);

	$cat->catlist = $categories;

	HTML_joigallery::editCategory($cat, $params);
}

function save_category() {
	global $database, $task, $option, $my, $Itemid;

	if (!$my->id && $my->gid != 2) {
		mosNotAuth();
		return;
	}

	$row = new joiGalleryCategory($database);
	$row->bind($_POST);

	if (!$row->id) {
		$row->ordering = 999999999;
	}

	// avoid linking category to itself
	if ($row->parent_id == $row->id) {
		$row->parent_id = 0;
	}

	$row->section = 'com_joivideo';

	$row->published = intval(mosGetParam($_REQUEST, 'published', 0));

	if (!$row->check()) {
		echo "<script> alert('" . $row->getError() . "'); window.history.go(-1); </script>\n";
		exit();
	}
	if (!$row->store()) {
		echo "<script> alert('" . $row->getError() . "'); window.history.go(-1); </script>\n";
		exit();
	}

	$row->updateOrder('section = \'com_joivideo\'');

	switch ($task) {
		case 'apply':
			mosRedirect('index.php?option=' . $option . '&task=editCategory&cid=' . $row->id . '&Itemid=' . $Itemid);
			break;
		case 'save':
			mosRedirect('index.php?option=' . $option . '&act=categories&cid=' . $row->id . '&Itemid=' . $Itemid);
			break;
	}
}

function show_category($cid, $params) {
	global $my;

	$database = &database::getInstance();

	$cid = intval($cid);

	$cat = new joiGalleryCategory($database);
	$cat->load($cid);

	$photos = new joiGalleryPhoto($database);

	$cat->subcats = $cat->get_categories($cid, $params);
    
    //Если у категории есть подкатегории
    // и нужно выводить фотки из подкатегорий
    if(count($cat->subcats) && !$params->get('cat_view_subcats', 1)){
    	$cat->total = $photos->get_count_photos($cid, $params, $cat->subcats);
    	$photos->content = $photos->load_photos($cid, $params, $cat->subcats);        
    }
    else{
    	$cat->total = $photos->get_count_photos($cid, $params);
    	$photos->content = $photos->load_photos($cid, $params);        
    }

	HTML_joigallery::showCategory($cat, $photos, $params);
}

function remove_category($cid, $params) {
	global $my;

	if(!$params->_access->allow_me('del_cat', $my->_gid)) {
		joiGalleryError::error($params->_access->error('del_cat'));
	}

	$database = &database::getInstance();
	$cat = new joiGalleryCategory($database);

	$photos = new joiGalleryPhoto($database);

	$total_photos = $photos->check_photos_by_cat($cid);
	if ($total_photos > 0) {
		joiGalleryError::error(addslashes(_C_JOIGALLERY_CAT_DELETE_STILL_PHOTOS));
	}

	$total_subcats = $photos->check_subcats_by_cat($cid);
	if ($total_subcats > 0) {
		joiGalleryError::error(addslashes(_C_JOIGALLERY_CAT_DELETE_STILL_SUBCATS));
	}

	$cat->delete($cid);

	mosRedirect('index.php?option=' . $params->_option . '&amp;Itemid=' . $params->_Itemid);

}